package lab3;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {
    public static void main(String[] args) throws InterruptedException {
        String[] stringArr = {"甲","乙","丙"};
        int len = stringArr.length;
        LockThread[] threads = new LockThread[len];
        Condition[] conditions = new Condition[len];
        for (int i = 0; i < len; ++i){
            threads[i] = new LockThread(stringArr[i]);
            threads[i].setName("T"+(i+1));
            conditions[i] = LockThread.getLock().newCondition();
        }
        for (int i = 0; i < len; ++i){
            if (i == len - 1){
                threads[i].setLockCondition(conditions[i], conditions[0]);
            }else {
                threads[i].setLockCondition(conditions[i], conditions[i+1]);
            }
        }
        for (LockThread t : threads) {
            t.start();
        }
        Thread.sleep(100);
        LockThread.getLock().lock();
        conditions[0].signal();
        LockThread.getLock().unlock();
    }
}

class LockThread extends Thread{
    private static ReentrantLock lock = new ReentrantLock();
    Condition nextCondition;
    Condition myCondition;
    String s;
    public LockThread(String _s){
        this.s = _s;
    }

    public static ReentrantLock getLock(){
        return lock;
    }

    public void setLockCondition(Condition my, Condition next){
        myCondition = my;
        nextCondition = next;
    }

    @Override
    public void run() {
        while(true){
            lock.lock();
            try {
                myCondition.await();
                System.out.println(s);
                sleep(10);
                nextCondition.signal();
                lock.unlock();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}